package com.wsc.springbootmultidevdemo.msg.pubnsub;

import com.rabbitmq.client.*;
import com.wsc.springbootmultidevdemo.msg.ConnectionUtil;

import java.io.IOException;
import java.util.concurrent.TimeoutException;

/**
 * 消费者2
 */
public class Worker2 {
    public static void main(String[] args) throws IOException, TimeoutException {
            Connection connection = ConnectionUtil.getConnection();
            Channel channel = connection.createChannel();

            //同一时间只能接收一条消息
            channel.basicQos(1);

            String qName = "queue2";
            String exName = "fanout";

            channel.queueDeclare(qName,false,false,false,null);
            //声明交换机 FANOUT:广播
            channel.exchangeDeclare(exName, BuiltinExchangeType.FANOUT);
            //绑定队列
            channel.queueBind(qName,exName,"");
            System.out.println("Consumer is waiting for message");

            Consumer consumer = new DefaultConsumer(channel){
                @Override
                public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte[] body) throws IOException {
                    String message = new String(body,"UTF-8");
                    System.out.println("receive a message :"+message);
                }
            };
            channel.basicConsume(qName,true,consumer);
    }
}
